﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using SYcwpb.Helpers;
using SYcwpb.Models;
using SYcwpb.Access;

namespace SYcwpb.Views
{
    /// <summary>
    /// AssignBB.xaml 的交互逻辑
    /// </summary>
    public partial class AssignBB : Window
    {
        private static AssignBB _instance = null;

        private TimeTableAccess _timeTableAccess = new TimeTableAccess();

        private Dictionary<string, TimeTableModel> _dicDateToTimeTable = new Dictionary<string, TimeTableModel>();

        /// <summary>
        /// 序号对应的交路号名称
        /// </summary>
        private Dictionary<string, string> _dicIndexToString = new Dictionary<string, string>();

        private int Line = Convert.ToInt32(CONSTDATA.UserModel.Line);

        /// <summary>
        /// 交路个数
        /// </summary>
        private int _crsRoadTotalCount = 0;

        private int _gridContentRows = 0;

        /// <summary>
        /// 总天数
        /// </summary>
        private int _totalDays = 0;

        /// <summary>
        /// 总列数
        /// </summary>
        private int _columns = 0;

        /// <summary>
        /// 表头行数
        /// </summary>
        private int _headrows = 3;

        string[] groups = {"白班","夜班","早班","休班"};

        Color _grid1Color = Colors.Bisque;
        Color _grid2Color = Colors.LightGray;
        Color _grid3Color = Colors.Pink;
        Color _grid4Color = Colors.PaleGreen;

        double _longWidth = 110;
        double _normalWidth = 55;
        double _shortWidth = 40;

        TextBox[][] tbs_head1;
        TextBox[][] tbs_head2;
        TextBox[][] tbs_head3;
        TextBox[][] tbs_head4;

        TextBox[][] tbs_content1;
        TextBox[][] tbs_content2;
        TextBox[][] tbs_content3;
        TextBox[][] tbs_content4;


        private AssignBB()
        {
            InitializeComponent();
        }

        public static AssignBB GetInsatance()
        {
            if (_instance == null || WindowHelper.IsDisposed(_instance))
                _instance = new AssignBB();

            return _instance;
        }

      

        private void InitStartDated()
        {
            this.dp_start.DisplayDateStart = DateTime.Now;
            
        }

        private bool CheckParaValidated()
        {
            bool result = false;

            if (string.IsNullOrEmpty(this.tb_jiaolu.Text))
            {
                MessageBoxHelper.ShowError("请输入交路个数！");
                return result;
            }

            if (!GlobalVariables.IsNumberic(this.tb_jiaolu.Text))
            {
                MessageBoxHelper.ShowError("参数格式有误，请确认！");
                return result;
            }

            this._crsRoadTotalCount = Convert.ToInt32(this.tb_jiaolu.Text);
            if (_crsRoadTotalCount > 40)
            {
                MessageBoxHelper.ShowError("当前交路数最大为40，请确认后输入有效数字！");
                return result;
            }

            result = true;

            return result;
        }

        private void InitDicDateToTimeTable()
        {
            _dicDateToTimeTable.Clear();

            DataTable dateToTableDt = _timeTableAccess.GetTableBetween(Convert.ToDateTime(dp_start.SelectedDate).ToString("yyyy-MM-dd"),Convert.ToDateTime(dp_end.SelectedDate).ToString("yyyy-MM-dd"),Line);
            if (dateToTableDt == null)
                return;

            TimeSpan diff = (DateTime)dp_end.SelectedDate - (DateTime)dp_start.SelectedDate;
            this._totalDays = diff.Days + 1 ;

            this._columns = _totalDays + 3;

            string filter = "";
            DateTime nextDate = (DateTime)dp_start.SelectedDate;
            for (int i = 1; i <= _totalDays; i ++ )
            {
                string date = nextDate.ToString("yyyy-MM-dd");
                filter = "Date = '" + date + "'";
                DataRow[] row = dateToTableDt.Select(filter);

                if (row != null && row.Length > 0)
                {
                    TimeTableModel model = TimeTableModel.CreateCSVFileModel();
                    model.ID = row[0]["ID"].ToString();
                    model.Name = row[0]["Name"].ToString();

                    _dicDateToTimeTable.Add(date, model);
                }
                else
                    _dicDateToTimeTable.Add(date, null);

                nextDate = nextDate.AddDays(1);
            }

        }

        private void InitDicIndexToString()
        {
            _dicIndexToString.Clear();

            string scxIndex = GetParaValue(tb_scx_index.Text);
            string dcIndex = GetParaValue(tb_dc_index.Text);
            string rbIndex = GetParaValue(tb_rb_index.Text);
            string bbIndex = GetParaValue(tb_bb_index.Text);

            string indexValue;
            for (int i = 1,index = 1; i <= _crsRoadTotalCount; i++ )
            {
                if (i.ToString() == scxIndex)
                    indexValue = "试车线";
                else if (i.ToString() == dcIndex)
                    indexValue = "调车";
                else if (i.ToString() == rbIndex)
                    indexValue = "热备";
                else if (i.ToString() == bbIndex)
                    indexValue = "备班";
                else
                {
                    indexValue = index.ToString();

                    index++;
                }

                _dicIndexToString.Add(i.ToString(), indexValue);
            }
        }

        private string GetParaValue(string source)
        {
            string result = "";

            if (!string.IsNullOrEmpty(source) && GlobalVariables.IsNumberic(source))
            {
                result = source;
            }

            return result;
        }

        private void InitTextBoxHead()
        {
            Thickness tnssNormal = new Thickness(2, 0, 2, 0);

            tbs_head1 = new TextBox[_headrows][];
            tbs_head2 = new TextBox[_headrows][];
            tbs_head3 = new TextBox[_headrows][];
            tbs_head4 = new TextBox[_headrows][];

            for (int i = 0; i < _headrows; i ++ )
            {
                tbs_head1[i] = new TextBox[_columns];
                tbs_head2[i] = new TextBox[_columns];
                tbs_head3[i] = new TextBox[_columns];
                tbs_head4[i] = new TextBox[_columns];
            }

            grid1_head.Children.Clear();
            grid2_head.Children.Clear();
            grid3_head.Children.Clear();
            grid4_head.Children.Clear();

            for (int i = 0; i < _columns; i ++ )
            {
                grid1_head.ColumnDefinitions.Add(GetNewColumn());
                grid2_head.ColumnDefinitions.Add(GetNewColumn());
                grid3_head.ColumnDefinitions.Add(GetNewColumn());
                grid4_head.ColumnDefinitions.Add(GetNewColumn());
            }

            for (int i = 0; i < _headrows; i++)
            {
                grid1_head.RowDefinitions.Add(GetNewRow());
                grid2_head.RowDefinitions.Add(GetNewRow());
                grid3_head.RowDefinitions.Add(GetNewRow());
                grid4_head.RowDefinitions.Add(GetNewRow());
            }

            for (int i = 0; i < _headrows; i ++ )
            {
                for (int k = 0; k < _columns; k ++ )
                {
                    if (0 < k)
                        tbs_head1[i][k] = GetTextBox(_longWidth, _grid1Color, tnssNormal);
                    else
                        tbs_head1[i][k] = GetTextBox(_shortWidth, _grid1Color, tnssNormal);

                    this.SetGridRowAndColumn(grid1_head, tbs_head1[i][k], i, k);

                    if (0 < k)
                        tbs_head2[i][k] = GetTextBox(_longWidth, _grid2Color, tnssNormal);
                    else
                        tbs_head2[i][k] = GetTextBox(_shortWidth, _grid2Color, tnssNormal);

                    this.SetGridRowAndColumn(grid2_head, tbs_head2[i][k], i, k);

                    if (0 < k)
                        tbs_head3[i][k] = GetTextBox(_longWidth, _grid3Color, tnssNormal);
                    else
                        tbs_head3[i][k] = GetTextBox(_shortWidth, _grid3Color, tnssNormal);

                    this.SetGridRowAndColumn(grid3_head, tbs_head3[i][k], i, k);

                    if (0 < k)
                        tbs_head4[i][k] = GetTextBox(_longWidth, _grid4Color, tnssNormal);
                    else
                        tbs_head4[i][k] = GetTextBox(_shortWidth, _grid4Color, tnssNormal);

                    this.SetGridRowAndColumn(grid4_head, tbs_head4[i][k], i, k);

                }
            }

        }

        private void InitHeadDate()
        {
            DateTime nextDate = (DateTime)dp_start.SelectedDate;
            string tempStringDate;
            string tempName;

            TimeTableModel timeTable = null;
            int groupIndex = 0;

            for (int col = 3; col < _columns; col ++ )
            {
                tempStringDate = nextDate.ToString("yyyy-MM-dd");

                for (int row = 0; row < _headrows; row ++ )
                {
                    if (row == 0)
                    {
                        tbs_head1[row][col].Text = nextDate.ToString("M月d日");
                        tbs_head2[row][col].Text = nextDate.ToString("M月d日");
                        tbs_head3[row][col].Text = nextDate.ToString("M月d日");
                        tbs_head4[row][col].Text = nextDate.ToString("M月d日");
                    }
                    else if (row == 1)
                    {
                        _dicDateToTimeTable.TryGetValue(tempStringDate, out timeTable);
                        if (null != timeTable)
                            tempName = string.Format("{0}",timeTable.Name);
                        else
                            tempName = string.Format("{0}", "(无)");

                        tbs_head1[row][col].Text = tempName;
                        tbs_head2[row][col].Text = tempName;
                        tbs_head3[row][col].Text = tempName;
                        tbs_head4[row][col].Text = tempName;

                        timeTable = null;
                    }
                    else  // row == 2
                    {
                        tbs_head1[row][col].Text = groups[groupIndex];
                        tbs_head2[row][col].Text = groups[(groupIndex + 1) % 4];
                        tbs_head3[row][col].Text = groups[(groupIndex + 2) % 4];
                        tbs_head4[row][col].Text = groups[(groupIndex + 3) % 4];

                        groupIndex = (groupIndex + 1) % 4;
                    }
                }

                nextDate = nextDate.AddDays(1);
            }
        }

        private void InitTextBoxContent()
        {
            _gridContentRows = _crsRoadTotalCount + 1;  //添加一行作为标注栏

            _columns = _totalDays * 2 + 3;

            Thickness tnssNormal = new Thickness(2,0,2,0);
            Thickness tnssOther = new Thickness(1, 0, 1, 0);

            tbs_content1 = new TextBox[_gridContentRows][];
            tbs_content2 = new TextBox[_gridContentRows][];
            tbs_content3 = new TextBox[_gridContentRows][];
            tbs_content4 = new TextBox[_gridContentRows][];

            for (int i = 0; i < _gridContentRows; i ++ )
            {
                tbs_content1[i] = new TextBox[_columns];
                tbs_content2[i] = new TextBox[_columns];
                tbs_content3[i] = new TextBox[_columns];
                tbs_content4[i] = new TextBox[_columns];
            }

            grid1_content.Children.Clear();
            grid2_content.Children.Clear();
            grid3_content.Children.Clear();
            grid4_content.Children.Clear();

            for (int i = 0; i < _columns; i ++ )
            {
                grid1_content.ColumnDefinitions.Add(GetNewColumn());
                grid2_content.ColumnDefinitions.Add(GetNewColumn());
                grid3_content.ColumnDefinitions.Add(GetNewColumn());
                grid4_content.ColumnDefinitions.Add(GetNewColumn());
            }

            for (int i = 0; i < _columns; i++)
            {
                grid1_content.RowDefinitions.Add(GetNewRow());
                grid2_content.RowDefinitions.Add(GetNewRow());
                grid3_content.RowDefinitions.Add(GetNewRow());
                grid4_content.RowDefinitions.Add(GetNewRow());
            }

            for (int i = 0; i < _gridContentRows; i ++ )
            {
                for (int k = 0; k < _columns; k ++ )
                {
                    if (k < 1)
                        tbs_content1[i][k] = GetTextBox(_shortWidth, _grid1Color, tnssNormal);
                    else if (k < 3)
                        tbs_content1[i][k] = GetTextBox(_longWidth, _grid1Color,tnssNormal);
                    else
                        tbs_content1[i][k] = GetTextBox(_normalWidth,_grid1Color,tnssOther);

                    this.SetGridRowAndColumn(grid1_content, tbs_content1[i][k], i, k);

                    if (k < 1)
                        tbs_content2[i][k] = GetTextBox(_shortWidth, _grid2Color, tnssNormal);
                    else if (k < 3)
                        tbs_content2[i][k] = GetTextBox(_longWidth, _grid2Color, tnssNormal);
                    else
                        tbs_content2[i][k] = GetTextBox(_normalWidth, _grid2Color, tnssOther);

                    this.SetGridRowAndColumn(grid2_content, tbs_content2[i][k], i, k);

                    if (k < 1)
                        tbs_content3[i][k] = GetTextBox(_shortWidth, _grid3Color, tnssNormal);
                    else if (k < 3)
                        tbs_content3[i][k] = GetTextBox(_longWidth, _grid3Color, tnssNormal);
                    else
                        tbs_content3[i][k] = GetTextBox(_normalWidth, _grid3Color, tnssOther);

                    this.SetGridRowAndColumn(grid3_content, tbs_content3[i][k], i, k);

                    if (k < 1)
                        tbs_content4[i][k] = GetTextBox(_shortWidth, _grid4Color, tnssNormal);
                    else if (k < 3)
                        tbs_content4[i][k] = GetTextBox(_longWidth, _grid4Color, tnssNormal);
                    else
                        tbs_content4[i][k] = GetTextBox(_normalWidth, _grid4Color, tnssOther);

                    this.SetGridRowAndColumn(grid4_content, tbs_content4[i][k], i, k);
                }
            }
        }

        private void InitTextBoxContentData()
        {
            tbs_content1[0][0].Text = "序号";
            tbs_content2[0][0].Text = "序号";
            tbs_content3[0][0].Text = "序号";
            tbs_content4[0][0].Text = "序号";

            tbs_content1[0][1].Text = tbs_content1[0][2].Text = "司机";
            tbs_content2[0][1].Text = tbs_content2[0][2].Text = "司机";
            tbs_content3[0][1].Text = tbs_content3[0][2].Text = "司机";
            tbs_content4[0][1].Text = tbs_content4[0][2].Text = "司机";

            //表头
            DateTime nextdate = (DateTime)dp_start.SelectedDate;
            for (int i = 3; i < _columns; i ++ )
            {
                if (i % 2 == 0)
                {
                    tbs_content1[0][i].Text = tbs_content2[0][i].Text = tbs_content3[0][i].Text = tbs_content4[0][i].Text = "备注";
                }
                else
                {
                    tbs_content1[0][i].Text = tbs_content2[0][i].Text = tbs_content3[0][i].Text = tbs_content4[0][i].Text = nextdate.ToString("dddd");

                    nextdate = nextdate.AddDays(1);
                }
            }

            FillData(tbs_head1, tbs_content1);
            FillData(tbs_head2, tbs_content2);
            FillData(tbs_head3, tbs_content3);
            FillData(tbs_head4, tbs_content4);

        }

        private void FillData(TextBox[][] tbs_head, TextBox[][] tbs_content)
        {
            int headcolIndex;
            int startIndex = 1;  //每列开始序号
            int curIndex = 0;    //每列当前序号
            string curGroup;

            //最后一序号不参与轮转，一直为最大那个数字
            for (int i = 3; i < _columns;)
            {
                headcolIndex = (i + 3) / 2;

                curGroup = tbs_head[2][headcolIndex].Text;

                if (curGroup == "白班" && i != 3)
                {
                    startIndex++;
                    if (startIndex > _crsRoadTotalCount)
                        startIndex = startIndex % _crsRoadTotalCount;
                }

                if (curGroup == "休班")
                {
                    for (int k = 1; k < _gridContentRows; k++)
                        tbs_content[k][i].Text = "休";
                }
                else
                {
                    for (int k = 1; k < _gridContentRows; k++)
                    {
                        curIndex = startIndex + k - 1;
                        if (curIndex > _crsRoadTotalCount - 1)
                            curIndex = curIndex % (_crsRoadTotalCount - 1 );

                        if ( k == _gridContentRows - 1)
                            tbs_content[k][i].Text = _crsRoadTotalCount.ToString();  //备班不参与轮转
                        else
                            tbs_content[k][i].Text = curIndex.ToString();
                    }
                }
                
                i = i + 2;
            }

        }


        private void btn_assign_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckParaValidated())
                return;

            InitDicDateToTimeTable();

            InitDicIndexToString();

            InitTextBoxHead();

            InitHeadDate();

            InitTextBoxContent();

            InitTextBoxContentData();
        }

        private ColumnDefinition GetNewColumn()
        {
            return new ColumnDefinition();
        }

        private RowDefinition GetNewRow()
        {
            return new RowDefinition();
        }

        private TextBox GetTextBox(double width,Color color,Thickness thicknewss)
        {
            TextBox tb = new TextBox();

            tb.Width = width;
            tb.Background = new SolidColorBrush(color);

            tb.TextAlignment = TextAlignment.Center;
            tb.HorizontalAlignment = HorizontalAlignment.Stretch;
            tb.FontSize = 14;
            tb.Margin = thicknewss;
            //tb.Margin = new Thickness(2,0,2,0);
            return tb;
        }

        private void SetGridRowAndColumn(Grid grid,TextBox tb,int row,int col)
        {
            grid.Children.Add(tb);
            Grid.SetRow(tb, row);
            Grid.SetColumn(tb, col);
        }

        private void btn_save_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitStartDated();
        }
    }
}
